import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { HttpClient, HttpErrorResponse, HttpParams } from '@angular/common/http';
import { SharedModule } from '../../shared/shared.module';
import { Router, RouterModule } from '@angular/router';
import { PagedResultDto } from '@abp/ng.core';
import { ExcelExportService } from '../../shared/services/excel-export.service';
import { StockDataService } from '../../shared/services/stock-data.service';
declare var bootstrap: any; // 添加Bootstrap类型声明

// 库存分布数据接口
interface StockDistributionDto {
  warehouseName: string;
  areaName: string;
  shelfNo: string;
  quantity: number;
  amount: number;
  percentage: number;
}

interface KucunZhuXinxiDto {
  id: number;
  serialNumber: number;
  goodsCode: string;
  goodsName: string;
  status: string;
  goodsType: string;
  specification: string;
  unit: string;
  barcode: string;
  warehouseName: string;
  locationName: string;
  currentStock: number;
  stockAmount: number;
  toBeStored: number;
  toBeShipped: number;
  availableStock: number;
  availableStockAmount: number;
  initialStock: number;
  finalStock: number;
}

interface KucunZhuXinxiQueryParams {
  GoodsCodeOrName?: string;
  GoodsType?: string;
  Unit?: string;
  WarehouseName?: string;
  Barcode?: string;
  IsDisabled?: boolean;
  IsZeroStock?: boolean;
  SkipCount: number;
  MaxResultCount: number;
  Sorting?: string;
}

@Component({
  selector: 'app-kucun-zhu-xinxi',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    SharedModule,
    RouterModule
  ],
  templateUrl: './kucun-zhu-xinxi.component.html',
  styleUrls: ['./kucun-zhu-xinxi.component.scss']
})
export class KucunZhuXinxiComponent implements OnInit {
  // 使Math可在模板中访问
  Math = Math;
  
  // 日期筛选选项
  dateFilterOptions = [
    { label: '今日', value: 'today', active: true },
    { label: '昨日', value: 'yesterday', active: false },
    { label: '本周', value: 'thisWeek', active: false },
    { label: '上周', value: 'lastWeek', active: false },
    { label: '本月', value: 'thisMonth', active: false },
    { label: '上月', value: 'lastMonth', active: false },
    { label: '自定义时间', value: 'custom', active: false }
  ];

  // 查询参数 - 注意参数名称首字母大写，与Swagger保持一致
  queryParams: KucunZhuXinxiQueryParams = {
    SkipCount: 0,
    MaxResultCount: 30,
    Sorting: ''
  };

  // 页码和页大小设置
  pageIndex = 1;
  pageSize = 30;
  total = 0;
  pageSizeOptions = [10, 20, 30, 50]; // 添加页大小选项
  inputPageNumber = 1; // 跳转页码输入
  
  // 列表状态
  list = {
    page: 1, // 当前页码
  };
  
  // 最大页数
  get maxPageCount(): number {
    return Math.ceil(this.total / this.pageSize) || 1;
  }

  // 库存数据
  dataList: KucunZhuXinxiDto[] = [];
  
  // 统计数据
  statistics = {
    totalStock: 0,
    totalAmount: 0,
    totalInStock: 0,
    totalOutStock: 0,
    totalPendingIn: 0,
    totalPendingOut: 0
  };

  // 货品类型选项
  goodsTypeOptions: string[] = [];
  
  // 单位选项
  unitOptions: string[] = [];
  
  // 仓库名称选项
  warehouseOptions: string[] = [];

  // 添加属性存储所有可能的选项值
  allGoodsTypeOptions: string[] = [];
  allUnitOptions: string[] = [];
  allWarehouseOptions: string[] = [];

  loading = false;
  apiError = false;
  errorMessage = '';
  exporting = false; // 添加导出状态标记

  // 库存分布相关属性
  selectedItem: KucunZhuXinxiDto | null = null;
  stockDistributions: StockDistributionDto[] = [];
  stockDistributionModal: any;

  constructor(
    private http: HttpClient, 
    private router: Router, 
    private excelExportService: ExcelExportService,
    private stockDataService: StockDataService
  ) {}

  ngOnInit(): void {
    // 首先加载所有可能的选项
    this.loadAllOptions();
    
    // 然后加载数据
    this.loadData();
    
    // 初始化模态框
    document.addEventListener('DOMContentLoaded', () => {
      const modalElement = document.getElementById('stockDistributionModal');
      if (modalElement) {
        this.stockDistributionModal = new bootstrap.Modal(modalElement);
      }
    });
  }

  // 加载所有可能的下拉框选项（不受筛选条件限制）
  loadAllOptions(): void {
    // 首先尝试使用专门的API获取所有选项
    const optionsApiUrl = '/api/app/kucun-zhu-xinxi/options';
    
    // 备用API，如果专门的API不存在，则使用主列表API但获取大量数据
    const mainApiUrl = '/api/app/kucun-zhu-xinxi';
    
    // 参数设置为获取尽可能多的数据
    const params = new HttpParams()
      .set('SkipCount', '0')
      .set('MaxResultCount', '1000'); // 获取尽可能多的数据
    
    // 尝试调用专门的API
    this.http.get<any>(optionsApiUrl).subscribe({
      next: (response) => {
        console.log('选项API返回数据:', response);
        if (response && response.goodsTypes && response.units && response.warehouses) {
          // 如果API返回了预期的格式
          this.allGoodsTypeOptions = response.goodsTypes.filter(Boolean);
          this.allUnitOptions = response.units.filter(Boolean);
          this.allWarehouseOptions = response.warehouses.filter(Boolean);
          
          // 更新下拉框选项
          this.goodsTypeOptions = [...this.allGoodsTypeOptions];
          this.unitOptions = [...this.allUnitOptions];
          this.warehouseOptions = [...this.allWarehouseOptions];
        } else {
          console.warn('API返回数据格式不符合预期，使用默认选项');
          this.setDefaultOptions();
        }
      },
      error: (error) => {
        console.error('选项API调用失败:', error);
        
        // 设置API错误状态，但继续使用默认选项
        this.apiError = true;
        this.errorMessage = '获取选项数据失败，使用默认选项。如果问题持续存在，请联系系统管理员。';
              
        // 立即设置默认选项
              this.setDefaultOptions();
        
        // 如果专门的API失败，不尝试使用主列表API，直接使用默认选项，以避免级联错误
        // 这里移除了之前的主API调用
      }
    });
  }
  
  // 设置默认选项
  setDefaultOptions(): void {
    // 货品类型默认选项
    this.allGoodsTypeOptions = ['办公设备', '食品饮料', '电子产品', '办公用品', '家用类'];
    this.goodsTypeOptions = [...this.allGoodsTypeOptions];
    
    // 单位默认选项
    this.allUnitOptions = ['个', '件', '箱', '盒', '套', '双', '瓶', '斤', 'kg', '吨'];
    this.unitOptions = [...this.allUnitOptions];
    
    // 仓库名称默认选项
    this.allWarehouseOptions = ['主仓库', '办公仓库', '食品仓库', '仓区-01', '仓区-02', '仓区-03', '北京仓', '上海仓', '广州仓'];
    this.warehouseOptions = [...this.allWarehouseOptions];
  }

  // 切换日期筛选
  onDateFilterChange(option: any): void {
    this.dateFilterOptions.forEach(opt => opt.active = false);
    option.active = true;
    this.loadData();
  }

  // 重置筛选条件
  reset(): void {
    this.queryParams = {
      SkipCount: 0,
      MaxResultCount: this.pageSize,
      Sorting: ''
    };
    this.pageIndex = 1;
    this.list.page = 1;
    
    // 重置后恢复所有选项
    this.goodsTypeOptions = [...this.allGoodsTypeOptions];
    this.unitOptions = [...this.allUnitOptions];
    this.warehouseOptions = [...this.allWarehouseOptions];
    
    this.loadData();
  }

  // 加载下拉选项数据
  loadOptions(): void {
    // 使用当前表格数据更新下拉框选项
    const currentGoodsTypes = [...new Set(this.dataList.map(item => item.goodsType))].filter(Boolean);
    const currentUnits = [...new Set(this.dataList.map(item => item.unit))].filter(Boolean);
    const currentWarehouses = [...new Set(this.dataList.map(item => item.warehouseName))].filter(Boolean);
    
    // 如果我们已经有了所有可能的选项，使用它们
    if (this.allGoodsTypeOptions.length > 0) {
      this.goodsTypeOptions = [...this.allGoodsTypeOptions];
    } else if (currentGoodsTypes.length > 0) {
      this.goodsTypeOptions = currentGoodsTypes;
    } else {
      this.goodsTypeOptions = ['办公设备', '食品饮料', '电子产品'];
    }
    
    if (this.allUnitOptions.length > 0) {
      this.unitOptions = [...this.allUnitOptions];
    } else if (currentUnits.length > 0) {
      this.unitOptions = currentUnits;
    } else {
      this.unitOptions = ['个', '件', '箱', '盒', '套', '双', '瓶', '斤', 'kg', '吨'];
    }
    
    if (this.allWarehouseOptions.length > 0) {
      this.warehouseOptions = [...this.allWarehouseOptions];
    } else if (currentWarehouses.length > 0) {
      this.warehouseOptions = currentWarehouses;
    } else {
      this.warehouseOptions = ['主仓库', '办公仓库', '食品仓库'];
    }
  }

  // 加载库存数据
  loadData(): void {
    this.loading = true;
    this.apiError = false;
    
    this.queryParams.SkipCount = (this.pageIndex - 1) * this.pageSize;
    this.queryParams.MaxResultCount = this.pageSize;
    
    const apiUrl = '/api/app/kucun-zhu-xinxi';
    
    // 创建HttpParams对象，确保参数名称正确
    let params = new HttpParams();
    
    // 添加查询参数
    if (this.queryParams.GoodsCodeOrName) {
      params = params.set('GoodsCodeOrName', this.queryParams.GoodsCodeOrName);
    }
    if (this.queryParams.GoodsType) {
      params = params.set('GoodsType', this.queryParams.GoodsType);
    }
    if (this.queryParams.Unit) {
      params = params.set('Unit', this.queryParams.Unit);
    }
    if (this.queryParams.WarehouseName) {
      params = params.set('WarehouseName', this.queryParams.WarehouseName);
    }
    if (this.queryParams.Barcode) {
      params = params.set('Barcode', this.queryParams.Barcode);
    }
    if (this.queryParams.IsDisabled !== undefined) {
      params = params.set('IsDisabled', this.queryParams.IsDisabled.toString());
    }
    if (this.queryParams.IsZeroStock !== undefined) {
      params = params.set('IsZeroStock', this.queryParams.IsZeroStock.toString());
    }
    
    // 必须的分页参数
    params = params.set('SkipCount', this.queryParams.SkipCount.toString());
    params = params.set('MaxResultCount', this.queryParams.MaxResultCount.toString());
    
    if (this.queryParams.Sorting) {
      params = params.set('Sorting', this.queryParams.Sorting);
    }
    
    console.log('发送请求参数:', params.toString());
    
    this.http.get<PagedResultDto<KucunZhuXinxiDto>>(apiUrl, { params })
      .subscribe({
        next: (response) => {
          console.log('API返回数据:', response);
          if (response && response.items) {
          this.dataList = response.items;
          this.total = response.totalCount;
          this.calculateStatistics();
            this.apiError = false;
          
          // 加载数据成功后，更新下拉框选项
          this.loadOptions();
            
            // 通知库存数据服务更新数据
            this.stockDataService.notifyDataChanged(this.dataList);
          } else {
            console.warn('API返回数据格式不符合预期');
            this.apiError = true;
            this.errorMessage = '服务器返回数据格式不正确';
            this.loading = false;
          }
          this.loading = false;
        },
        error: (error) => {
          console.error('API调用失败:', error);
          this.apiError = true;
          this.errorMessage = '加载数据失败，如果问题持续存在，请联系系统管理员。';
          this.loading = false;
        }
      });
  }

  // 计算统计数据
  calculateStatistics(): void {
    let totalStock = 0;
    let totalAmount = 0;
    let totalAvailable = 0;
    
    this.dataList.forEach(item => {
      totalStock += item.currentStock || 0;
      totalAmount += item.stockAmount || 0;
      totalAvailable += item.availableStock || 0;
    });
    
    this.statistics.totalStock = totalStock;
    this.statistics.totalAmount = totalAmount;
    
    // 设置待入库和待出库数量
    let totalToBeStored = 0;
    let totalToBeShipped = 0;
    
    this.dataList.forEach(item => {
      totalToBeStored += item.toBeStored || 0;
      totalToBeShipped += item.toBeShipped || 0;
    });
    
    this.statistics.totalPendingIn = totalToBeStored;
    this.statistics.totalPendingOut = totalToBeShipped;
    
    // 设置入库和出库数量，这个需要根据业务需求调整
    this.statistics.totalInStock = Math.round(totalStock * 0.6);  // 示例: 60%入库
    this.statistics.totalOutStock = Math.round(totalStock * 0.4);  // 示例: 40%出库
  }

  // 页码变更
  pageIndexChange(index: number): void {
    if (index < 1 || index > this.maxPageCount) {
      return;
    }
    this.pageIndex = index;
    this.list.page = index;
    this.inputPageNumber = index;
    this.loadData();
  }

  // 页大小变更
  pageSizeChange(size: number): void {
    this.pageSize = Number(size);
    this.pageIndex = 1;
    this.list.page = 1;
    this.loadData();
  }
  
  // 处理页码输入变化
  onPageInputChange(event: any): void {
    let page = parseInt(event.target.value);
    if (isNaN(page)) {
      page = 1;
    }
    if (page < 1) {
      page = 1;
    }
    if (page > this.maxPageCount) {
      page = this.maxPageCount;
    }
    this.inputPageNumber = page;
  }
  
  // 处理页码输入回车
  onPageInputKeyUp(event: KeyboardEvent): void {
    if (event.key === 'Enter') {
      this.goToPage(this.inputPageNumber);
    }
  }
  
  // 跳转到指定页
  goToPage(page: number): void {
    this.pageIndexChange(page);
  }

  // 搜索
  search(): void {
    this.pageIndex = 1;
    this.list.page = 1;
    this.loadData();
  }

  // 出入库操作
  handleStockOperation(item: KucunZhuXinxiDto, operationType: 'in' | 'out'): void {
    console.log(`${operationType === 'in' ? '入库' : '出库'}操作`, item);
    // 这里可以打开出入库模态框
    alert(`${operationType === 'in' ? '入库' : '出库'}操作: ${item.goodsName}`);
  }

  // 库存分布操作
  handleStockDistribution(item: KucunZhuXinxiDto): void {
    console.log('库存分布操作', item);
    this.selectedItem = item;
    this.loadStockDistributions(item.goodsCode);
    
    // 如果模态框未初始化，则初始化
    if (!this.stockDistributionModal) {
      const modalElement = document.getElementById('stockDistributionModal');
      if (modalElement) {
        this.stockDistributionModal = new bootstrap.Modal(modalElement);
      }
    }
    
    // 显示模态框
    if (this.stockDistributionModal) {
      this.stockDistributionModal.show();
    } else {
      alert('无法显示库存分布模态框');
    }
  }
  
  // 加载库存分布数据
  loadStockDistributions(goodsCode: string): void {
    console.log('加载商品编码库存分布:', goodsCode);
    
    // 根据商品编码生成不同的库存分布数据
    let mockDistributions: StockDistributionDto[] = [];
    
    // 使用商品编码最后一位数字作为随机种子
    const lastChar = goodsCode.charAt(goodsCode.length - 1);
    const seed = parseInt(lastChar) || 0;
    
    // 根据种子决定仓库数量和分布
    switch (seed % 3) {
      case 0:
        // 三个仓库分布
        mockDistributions = [
          { warehouseName: '北京仓', areaName: 'A区', shelfNo: 'A-01-01', quantity: 50 + seed * 10, amount: (50 + seed * 10) * 100, percentage: 40 },
          { warehouseName: '上海仓', areaName: 'B区', shelfNo: 'B-02-03', quantity: 40 + seed * 5, amount: (40 + seed * 5) * 100, percentage: 32 },
          { warehouseName: '广州仓', areaName: 'C区', shelfNo: 'C-05-02', quantity: 35 + seed * 2, amount: (35 + seed * 2) * 100, percentage: 28 }
        ];
        break;
      case 1:
        // 两个仓库分布
        mockDistributions = [
          { warehouseName: '北京仓', areaName: 'A区', shelfNo: 'A-03-05', quantity: 120 + seed * 5, amount: (120 + seed * 5) * 100, percentage: 65 },
          { warehouseName: '广州仓', areaName: 'D区', shelfNo: 'D-01-06', quantity: 65 + seed * 3, amount: (65 + seed * 3) * 100, percentage: 35 }
        ];
        break;
      case 2:
        // 四个仓库分布
        mockDistributions = [
          { warehouseName: '北京仓', areaName: 'A区', shelfNo: 'A-02-03', quantity: 30 + seed * 3, amount: (30 + seed * 3) * 100, percentage: 25 },
          { warehouseName: '上海仓', areaName: 'B区', shelfNo: 'B-01-02', quantity: 25 + seed * 4, amount: (25 + seed * 4) * 100, percentage: 20 },
          { warehouseName: '广州仓', areaName: 'C区', shelfNo: 'C-04-01', quantity: 40 + seed * 2, amount: (40 + seed * 2) * 100, percentage: 30 },
          { warehouseName: '成都仓', areaName: 'E区', shelfNo: 'E-01-05', quantity: 30 + seed * 1, amount: (30 + seed * 1) * 100, percentage: 25 }
        ];
        break;
    }
    
    // 重新计算各条数据的占比
    const totalQuantity = mockDistributions.reduce((sum, item) => sum + item.quantity, 0);
    mockDistributions = mockDistributions.map(item => {
      const percentage = Math.round((item.quantity / totalQuantity) * 100);
      return { ...item, percentage };
    });
    
    this.stockDistributions = mockDistributions;
    
    // 计算总库存并更新selectedItem
    if (this.selectedItem) {
      this.selectedItem = {
        ...this.selectedItem,
        currentStock: totalQuantity
      };
    }
    
    // 实际应用中应该调用API
    /*
    const apiUrl = `/api/app/stock-distribution/${goodsCode}`;
    this.http.get<StockDistributionDto[]>(apiUrl).subscribe({
      next: (response) => {
        this.stockDistributions = response;
        // 计算总库存为各仓库库存之和
        if (this.selectedItem) {
          const totalQuantity = this.stockDistributions.reduce((sum, item) => sum + item.quantity, 0);
          this.selectedItem = {
            ...this.selectedItem,
            currentStock: totalQuantity
          };
        }
      },
      error: (error) => {
        console.error('获取库存分布数据失败:', error);
        this.stockDistributions = [];
      }
    });
    */
  }

  // 修改跳转到出入库流水的方法
  navigateToChuRuKuLiuShui(item: KucunZhuXinxiDto): void {
    console.log('跳转到出入库流水页面，商品编码:', item.goodsCode);
    this.router.navigate(['/stock/chu-ru-ku-liu-shui'], {
      queryParams: {
        goodsCode: item.goodsCode
      }
    });
  }

  // 导出库存数据到Excel
  exportData(): void {
    // 如果正在导出中，则不处理
    if (this.exporting) {
      return;
    }
    
    try {
      // 设置导出状态
      this.exporting = true;
      
      // 定义Excel列配置
      const columns = [
        { header: '序号', key: 'serialNumber', width: 10 },
        { header: '货品编号', key: 'goodsCode', width: 15 },
        { header: '货品名称', key: 'goodsName', width: 20 },
        { header: '状态', key: 'status', width: 12 },
        { header: '货品类型', key: 'goodsType', width: 15 },
        { header: '规格型号', key: 'specification', width: 15 },
        { header: '单位', key: 'unit', width: 10 },
        { header: '条码', key: 'barcode', width: 18 },
        { header: '仓库名称', key: 'warehouseName', width: 15 },
        { header: '库位名称', key: 'locationName', width: 15 },
        { header: '当前库存', key: 'currentStock', width: 12 },
        { header: '库存金额', key: 'stockAmount', width: 15 },
        { header: '待入库', key: 'toBeStored', width: 12 },
        { header: '待出库', key: 'toBeShipped', width: 12 }
      ];
      
      // 如果当前页数据少于总数，则获取全部数据后再导出
      if (this.dataList.length < this.total) {
        // 准备导出全部数据的查询参数
        let exportParams = new HttpParams()
          .set('SkipCount', '0')
          .set('MaxResultCount', `${this.total}`); // 获取所有数据
        
        // 添加当前查询条件
        if (this.queryParams.GoodsCodeOrName) {
          exportParams = exportParams.set('GoodsCodeOrName', this.queryParams.GoodsCodeOrName);
        }
        if (this.queryParams.GoodsType) {
          exportParams = exportParams.set('GoodsType', this.queryParams.GoodsType);
        }
        if (this.queryParams.Unit) {
          exportParams = exportParams.set('Unit', this.queryParams.Unit);
        }
        if (this.queryParams.WarehouseName) {
          exportParams = exportParams.set('WarehouseName', this.queryParams.WarehouseName);
        }
        if (this.queryParams.Barcode) {
          exportParams = exportParams.set('Barcode', this.queryParams.Barcode);
        }
        if (this.queryParams.IsDisabled !== undefined) {
          exportParams = exportParams.set('IsDisabled', this.queryParams.IsDisabled.toString());
        }
        if (this.queryParams.IsZeroStock !== undefined) {
          exportParams = exportParams.set('IsZeroStock', this.queryParams.IsZeroStock.toString());
        }
        
        // 获取全部数据
        const apiUrl = '/api/app/kucun-zhu-xinxi';
        this.http.get<PagedResultDto<KucunZhuXinxiDto>>(apiUrl, { params: exportParams })
          .subscribe({
            next: async (response) => {
              if (response && response.items && response.items.length > 0) {
                console.log(`获取导出数据成功，共${response.items.length}条记录`);
                // 导出Excel
                await this.excelExportService.exportToExcel(
                  response.items, 
                  '库存主信息',
                  columns
                );
              } else {
                console.warn('没有数据可导出');
                alert('没有数据可导出');
              }
              this.exporting = false; // 重置导出状态
            },
            error: (error) => {
              console.error('获取导出数据失败:', error);
              alert('获取导出数据失败: ' + (error.message || '未知错误'));
              this.exporting = false; // 重置导出状态
            }
          });
      } else {
        // 直接导出当前页数据
        this.excelExportService.exportToExcel(
          this.dataList, 
          '库存主信息',
          columns
        ).then(() => {
          console.log('导出成功');
          this.exporting = false; // 重置导出状态
        }).catch(error => {
          console.error('导出失败:', error);
          alert('导出失败: ' + (error.message || '未知错误'));
          this.exporting = false; // 重置导出状态
        });
      }
    } catch (error: any) {
      console.error('导出过程出错:', error);
      alert('导出过程出错: ' + (error.message || '未知错误'));
      this.exporting = false; // 重置导出状态
    }
  }

  // 新增：手动刷新大屏数据
  refreshDashboard(): void {
    this.stockDataService.refreshData();
  }
} 